package com.lagou.spi.filter;

import com.lagou.bean.MonitorBean;
import com.lagou.util.TpMonitorUtil;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;

/**
 * <h1>Dubbo性能监控过滤器</h1>
 * @author yzh
 */
@Activate(group = {CommonConstants.PROVIDER})
public class TpMonitorFilter implements Filter {

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        long startTime = System.currentTimeMillis();
        String methodName = invocation.getMethodName();
        try {
            return invoker.invoke(invocation);
        } finally {
            //第一次执行完成后开始计时
            if(TpMonitorUtil.getInvokeTimeNum() == 0L) {
                TpMonitorUtil.startInvokeTimeNumCount();
            }
            long endTime = System.currentTimeMillis();
            long invokeTime = endTime - startTime;
            //执行结束后放到方法对应的队列中
            TpMonitorUtil.getQueue(methodName).
                add(new MonitorBean(startTime, endTime, invokeTime, TpMonitorUtil.getInvokeTimeNum()));
        }
    }
}
